import React, { useState, useEffect } from 'react';
import { Button, Table, Space, Image, Card, Input, Form, Modal, message, Upload, Typography, DatePicker, Tag, Radio } from 'antd';
import { PlusOutlined, SearchOutlined, PlayCircleOutlined, UploadOutlined, ScissorOutlined, DeleteOutlined, DownloadOutlined } from '@ant-design/icons';
import { ConfigProvider } from 'antd';
import locale from 'antd/locale/zh_CN';
import type { UploadFile } from 'antd/es/upload/interface';
import { uploadFile } from '@/services/FileService';
import {
  CelebrityStageCutInfo,
  getCelebrityStageCutInfoPage,
  addCelebrityStageCutInfo,
  updateCelebrityStageCutInfo,
  deleteCelebrityStageCutInfo,
} from '@/services/CelebrityStageCutInfo';
import styles from './index.less';
import { famousPersonId } from '@/services';
import dayjs from 'dayjs';
import {PLAY_BASE_URL} from '@/services/FileService'
const { TextArea } = Input;

const StageWorks: React.FC = () => {
  const [searchForm] = Form.useForm();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<CelebrityStageCutInfo[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingId, setEditingId] = useState<number | undefined>();
  const [videoFile, setVideoFile] = useState<UploadFile[]>([]);
  const [thumbnailFile, setThumbnailFile] = useState<UploadFile[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [videoElement, setVideoElement] = useState<HTMLVideoElement | null>(null);
  const [showThumbnailModal, setShowThumbnailModal] = useState(false);
  const [videoUploading, setVideoUploading] = useState(false);
  const [videoReady, setVideoReady] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewVideo, setPreviewVideo] = useState('');
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [currentVideoInfo, setCurrentVideoInfo] = useState<{ id: string; url: string; downloadable: number } | null>(null);

  // 加载数据
  const loadData = async (page = pagination.current, pageSize = pagination.pageSize) => {
    try {
      setLoading(true);
      const values = await searchForm.validateFields();
      const response = await getCelebrityStageCutInfoPage({
        pageCurrent: page,
        pageSize: pageSize,
        famousPersonId: famousPersonId,
        keyword: values.keyword,
      });
      setData(response.list);
      setPagination({
        current: page,
        pageSize: pageSize,
        total: response.totalCount,
      });
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  // 列定义
  const columns = [
    {
      title: '缩略图',
      dataIndex: 'thumbnailUrl',
      key: 'thumbnailUrl',
      width: '12%',
      render: (thumbnailUrl: string) => (
        thumbnailUrl ? (
          <Image
            src={thumbnailUrl}
            alt="缩略图"
            width={120}
            height={67}
            style={{ objectFit: 'cover', borderRadius: 4 }}
            preview={{
              mask: '预览',
              maskClassName: styles.previewMask,
            }}
          />
        ) : '-'
      ),
    },
    {
      title: '舞台名称',
      dataIndex: 'stageName',
      key: 'stageName',
      width: '15%',
      render: (text: string) => (
        <span style={{ color: '#1890ff', fontWeight: 500 }}>{text}</span>
      ),
    },
    {
      title: '活动名称',
      dataIndex: 'eventName',
      key: 'eventName',
      width: '15%',
    },
    {
      title: '时长',
      dataIndex: 'durationStr',
      key: 'durationStr',
      width: '8%',
    },
    {
      title: '来源',
      dataIndex: 'cr',
      key: 'cr',
      width: '10%',
    },
    {
      title: '观看次数',
      dataIndex: 'views',
      key: 'views',
      width: '8%',
    },
    {
      title: '上传日期',
      dataIndex: 'uploadDate',
      key: 'uploadDate',
      width: '12%',
    },
    {
      title: '标签',
      dataIndex: 'tags',
      key: 'tags',
      width: '15%',
      render: (text: string) => {
        if (!text) return '-';
        const tags = text.split(/[,，、]/g).filter(Boolean);
        return (
          <Space size={[0, 4]} wrap>
            {tags.map((tag, index) => (
              <Tag key={index} color="blue">{tag.trim()}</Tag>
            ))}
          </Space>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: '15%',
      render: (_: any, record: CelebrityStageCutInfo) => (
        <Space>
          <Button
            type="link"
            icon={<PlayCircleOutlined />}
            onClick={() => handleVideoPreview(record)}
            disabled={!record.videoInfo}
          >
            播放
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
          <Button type="link" danger onClick={() => handleDelete(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];

  // 处理视频预览
  const handleVideoPreview = (record: CelebrityStageCutInfo) => {
    setPreviewVideo(record.videoInfo.url);
    setCurrentVideoInfo({ id: record.videoInfo.id, url: record.videoInfo.url, downloadable: record.downloadable });
    setPreviewVisible(true);
  };

  // 处理删除
  const handleDelete = (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个舞台作品吗？删除后无法恢复。',
      okText: '确认',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await deleteCelebrityStageCutInfo([id]);
          message.success('删除成功');
          loadData();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理编辑
  const handleEdit = (record: CelebrityStageCutInfo) => {
    setEditingId(record.id);
    form.setFieldsValue({
      ...record,
      videoId: record.videoInfo.id,
      downloadable: record.downloadable,
      uploadDate: record.uploadDate && dayjs(record.uploadDate).isValid() ? dayjs(record.uploadDate) : undefined,
    });
    // 设置视频文件
    if (record.videoInfo) {
      setVideoFile([{
        uid: record.videoInfo.id.toString(),
        name: record.videoInfo.fileName || '视频文件',
        status: 'done',
        url: record.videoInfo.url,
        type: 'video/mp4',
      }]);
      setVideoReady(true);
    }

    // 设置缩略图
    if (record.thumbnailId) {
      setThumbnailFile([{
        uid: record.thumbnailId?.toString(),
        name: 'thumbnail',
        status: 'done',
        url: record.thumbnailUrl,
      }]);
    }

    setModalVisible(true);
  };

  // 处理取消
  const handleCancel = () => {
    setModalVisible(false);
    setEditingId(undefined);
    form.resetFields();
    setVideoFile([]);
    setThumbnailFile([]);
    setVideoReady(false);
  };

  // 处理文件上传
  const handleFileUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;
    try {
      const fileDetailVO = await uploadFile(file);
      if (fileDetailVO) {
        onSuccess({
          uid: fileDetailVO.id.toString(),
          name: fileDetailVO.fileName,
          status: 'done',
          url: fileDetailVO.url,
        });
      } else {
        onError(new Error('上传失败'));
      }
    } catch (error) {
      onError(error);
    }
  };

  // 修改视频文件状态变化处理
  const handleVideoChange = ({ file }: any) => {
    switch (file.status) {
      case 'uploading':
        setVideoUploading(true);
        setVideoFile([file]);
        break;

      case 'done':
        if (file.response) {
          const resp = file.response
          setVideoUploading(false);
          setVideoReady(true);
          setVideoFile([{
            uid: resp.uid.toString(),
            name: resp.name,
            status: 'done',
            url: resp.url,
            type: 'video/mp4',
          }]);
        }
        break;

      case 'error':
        setVideoUploading(false);
        setVideoReady(false);
        message.error('视频上传失败');
        setVideoFile([]);
        break;

      case 'removed':
        setVideoFile([]);
        setVideoReady(false);
        form.setFieldValue('videoId', undefined);
        break;
    }
  };

  // 渲染搜索表单
  const renderSearchForm = () => (
    <div className={styles.toolbarContent}>
      <Form
        form={searchForm}
        layout="inline"
        className={styles.searchForm}
        onFinish={handleSearch}
      >
        <Form.Item name="keyword">
          <Input
            placeholder="舞台名称/活动名称/描述"
            prefix={<SearchOutlined />}
            allowClear
            style={{ width: 250 }}
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
            <Button onClick={handleReset}>重置</Button>
          </Space>
        </Form.Item>
        <Form.Item>
          <Space style={{ marginLeft: 20 }}>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setModalVisible(true)}>
              添加舞台作品
            </Button>
          </Space>
        </Form.Item>
      </Form>

    </div>
  );

  // 处理搜索
  const handleSearch = async () => {
    setPagination(prev => ({ ...prev, current: 1 }));
    loadData(1, 20);
  };

  // 处理重置
  const handleReset = () => {
    searchForm.resetFields();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadData(1, 20);
  };

  // 修改视频截图功能
  const handleCapture = async () => {
    if (!videoElement) return;

    try {
      // 确保视频已经加载完成
      if (videoElement.readyState < 2) {
        message.warning('视频还未加载完成，请稍候');
        return;
      }

      const canvas = document.createElement('canvas');
      videoElement.crossOrigin = 'anonymous';
      canvas.width = videoElement.videoWidth;
      canvas.height = videoElement.videoHeight;
      const ctx = canvas.getContext('2d');

      if (!ctx) {
        message.error('浏览器不支持截图功能');
        return;
      }

      ctx.drawImage(videoElement, 0, 0);

      // 转换为Blob
      const blob = await new Promise<Blob | null>((resolve) => {
        canvas.toBlob((b) => resolve(b), 'image/png');
      });

      if (!blob) {
        message.error('截图失败');
        return;
      }

      const file = new File([blob], 'thumbnail.png', { type: 'image/png' });
      const fileDetailVO = await uploadFile(file);

      // 更新缩略图状态
      setThumbnailFile([{
        uid: fileDetailVO.id.toString(),
        name: 'thumbnail.png',
        status: 'done',
        url: fileDetailVO.url,
      }]);

      // 更新表单值
      form.setFieldValue('thumbnailId', fileDetailVO.id);

      setShowThumbnailModal(false);
      message.success('缩略图设置成功');

    } catch (error) {
      message.error('缩略图设置失败');
      console.error('截图错误:', error);
    }
  };

  // 修改缩略图模态框
  const renderThumbnailModal = () => {
    // 获取视频URL
    const getVideoUrl = () => {
      const videoData = videoFile[0];
      if (!videoData) return ''

      return `/api/file/play/${ videoData.uid}`;
    };

    return (
      <Modal
        title="截取视频缩略图"
        open={showThumbnailModal}
        onCancel={() => {
          setShowThumbnailModal(false);
          setVideoReady(false);
        }}
        destroyOnClose
        maskClosable={false}
        footer={[
          <Button key="cancel" onClick={() => {
            setShowThumbnailModal(false);
            setVideoReady(false);
          }}>
            取消
          </Button>,
          <Button
            key="capture"
            type="primary"
            onClick={handleCapture}
            disabled={!videoReady}
          >
            截取当前帧
          </Button>
        ]}
        width={800}
      >
        <div style={{ textAlign: 'center' }}>
          <video
            ref={setVideoElement}
            src={getVideoUrl()}
            controls
            style={{ maxWidth: '100%', maxHeight: '500px' }}
            onLoadedData={() => {
              setVideoReady(true);
              message.success('视频加载完成，可以开始截取');
            }}
            onError={(e) => {
              console.error('视频加载错误:', e);
              message.error('视频加载失败，请检查视频文件');
              setVideoReady(false);
            }}
          />
          <div style={{ marginTop: 16 }}>
            <Typography.Text type="secondary">
              提示：播放视频到合适的画面，点击&quot;截取当前帧&quot;按钮即可设置为缩略图
            </Typography.Text>
          </div>
        </div>
      </Modal>
    );
  };

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      const submitData = {
        ...values,
        famousPersonId,
        videoId: videoFile.length > 0 ? videoFile[0]?.uid : values.videoId,
        thumbnailId: thumbnailFile.length > 0
          ? thumbnailFile[0]?.response?.uid || thumbnailFile[0]?.uid
          : (editingId ? values.thumbnailId : null),
        tags: values.tags?.trim().replace(/[,，、;；]\s*/g, ',') || '',
        downloadable: values.downloadable,
        uploadDate: values.uploadDate ? values.uploadDate.format('YYYY-MM-DD') : null,
      };

      if (editingId) {
        await updateCelebrityStageCutInfo({ ...submitData, id: editingId });
        message.success('更新成功');
      } else {
        await addCelebrityStageCutInfo(submitData);
        message.success('添加成功');
      }
      handleCancel();
      loadData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 分页器变化处理函数
  const handleTableChange = (newPagination: any) => {
    loadData(newPagination.current, newPagination.pageSize);
  };
  // 图片预览处理函数
  const handleImagePreview = async (file: UploadFile) => {
    const fileDetailVO = file.response
    if (fileDetailVO) {
      const previewUrl = fileDetailVO.url;
      setPreviewImage(previewUrl);
      setPreviewOpen(true);
    } else {
      const previewUrl = file.url;
      setPreviewImage(previewUrl || '');
      setPreviewOpen(true);
    }
  };

  // 修改视频文件预览处理函数
  const handleVideoFilePreview = (file: UploadFile) => {
    setPreviewVideo(file.url || '');
    setPreviewVisible(true);
  };

  // 添加渲染表单模态框函数
  const renderModal = () => (
    <Modal
      title={editingId ? '编辑舞台作品' : '添加舞台作品'}
      open={modalVisible}
      onCancel={handleCancel}
      footer={null}
      width={800}
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
      >
        <Form.Item
          name="stageName"
          label="舞台名称"
          rules={[{ required: true, message: '请输入舞台名称' }]}
        >
          <Input maxLength={100} />
        </Form.Item>

        <Form.Item
          name="eventName"
          label="活动名称"
        >
          <Input maxLength={100} />
        </Form.Item>

        <Form.Item
          name="description"
          label="内容描述"
        >
          <TextArea rows={4} maxLength={500} showCount />
        </Form.Item>

        <Form.Item
          name="videoId"
          label="视频"
          rules={[{ required: true, message: '请上传视频' }]}
          initialValue={editingId ? form.getFieldValue('videoId') : undefined}
        >
          <div className={styles.videoUploadWrapper}>
            <Upload
              fileList={videoFile}
              onChange={handleVideoChange}
              customRequest={handleFileUpload}
              maxCount={1}
              accept="video/*"
              listType="picture-card" 
              onPreview={handleVideoFilePreview}
              onRemove={() => {
                setVideoFile([]);
                setVideoReady(false);
                form.setFieldValue('videoId', undefined);
                return true;
              }}
            >
              {videoFile.length === 0 && (
                <div className={styles.uploadButton}>
                  <div className={styles.uploadContent}>
                    <UploadOutlined className={styles.uploadIcon} />
                    <div className={styles.uploadText}>
                      {videoUploading ? '视频上传中...' : '点击上传视频'}
                    </div>
                  </div>
                </div>
              )}
            </Upload>
          </div>
        </Form.Item>

        <Form.Item
          name="thumbnailId"
          label="缩略图"
          extra="可以直接上传图片，或从视频中截取"
        >
          <Space direction="vertical" style={{ width: '100%' }}>
            <Upload
              listType="picture-card"
              fileList={thumbnailFile}
              onChange={({ fileList }) => {
                setThumbnailFile(fileList);
                if (fileList.length === 0) {
                  form.setFieldValue('thumbnailId', undefined);
                }
              }}
              customRequest={handleFileUpload}
              maxCount={1}
              accept="image/*"
              onRemove={() => {
                setThumbnailFile([]);
                form.setFieldValue('thumbnailId', undefined);
                return true;
              }}
              onPreview={handleImagePreview}
            >
              {thumbnailFile.length === 0 && '+ 上传缩略图'}
            </Upload>
            {videoFile.length > 0 && videoFile[0].status === 'done' && (
              <Button
                type="dashed"
                onClick={() => setShowThumbnailModal(true)}
                icon={<ScissorOutlined />}
              >
                从视频截取缩略图
              </Button>
            )}
          </Space>
        </Form.Item>

        <Form.Item
          name="tags"
          label="标签"
        >
          <Input placeholder="多个标签用逗号、顿号分隔（如：舞台、演唱会）" maxLength={100} />
        </Form.Item>

        <Form.Item
          name="cr"
          label="来源"
        >
          <Input maxLength={50} />
        </Form.Item>

        <Form.Item
          name="uploadDate"
          label="上传日期"
        >
          <DatePicker style={{ width: '100%' }} locale={locale.DatePicker} />
        </Form.Item>

        <Form.Item
          name="downloadable"
          label="下载控制"
          initialValue={1}
        >
          <Radio.Group>
            <Radio value={1}>允许下载</Radio>
            <Radio value={0}>禁止下载</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item className={styles.modalFooter}>
          <Space>
            <Button onClick={handleCancel}>取消</Button>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );

  // 添加视频预览模态框
  const renderPreviewModal = () => (
    <Modal
      title="视频预览"
      open={previewVisible}
      onCancel={() => {
        setPreviewVisible(false);
        setPreviewVideo('');
      }}
      onOk={() => {
        setPreviewVisible(false);
        setPreviewVideo('');
      }}
      width={800}
      destroyOnClose={true}
      centered
    >
      {previewVisible && (
        <video
          src={previewVideo}
          controls
          controlsList={currentVideoInfo?.downloadable === 0 ? "nodownload" : undefined}
          onContextMenu={e => currentVideoInfo?.downloadable === 0 && e.preventDefault()}
          style={{ width: '100%', maxHeight: '80vh'}}
          autoPlay
        />
      )}
    </Modal>
  );

  return (
    <ConfigProvider locale={locale}>
      <div className={styles.container}>
        <Card title="舞台作品管理">
          <div className={styles.toolbar}>
            {renderSearchForm()}
          </div>
          <Table
            columns={columns}
            dataSource={data}
            scroll={{ y: 'calc(100vh - 380px)', scrollToFirstRowOnChange: false }}
            rowKey="id"
            loading={loading}
            pagination={{
              ...pagination,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条`,
              pageSizeOptions: ['10', '20', '50', '100'],
            }}
            onChange={handleTableChange}
          />
          {renderModal()}
          {renderThumbnailModal()}
          {renderPreviewModal()}
          {previewImage && (
            <Image
              style={{ display: 'none' }}
              preview={{
                visible: previewOpen,
                src: previewImage,
                onVisibleChange: (visible) => {
                  setPreviewOpen(visible);
                  if (!visible) {
                    setPreviewImage('');
                  }
                },
              }}
            />
          )}
        </Card>
      </div>
    </ConfigProvider>
  );
};

export default StageWorks; 